package beans;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database implements Serializable {
	private static final long serialVersionUID = 1529925802879968933L;
	private volatile static Database instance;
	private String userName;
	private String password;
	private String host;
	private String port;
	private String dbName;
	private String url;

	private Database() throws ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		this.userName = "root";
		this.password = "0906";
		this.host = "localhost";
		this.port = "3306";
		this.dbName = "hiroom";
		this.url = new StringBuilder("jdbc:mysql://").append(host).append(":")
				.append(port).append("/").append(dbName)
				.append("?useUnicode=true&characterEncoding=UTF-8").toString();
	}

	public static Database getInstance() throws ClassNotFoundException {
		if (instance == null) {
			synchronized (Database.class) {
				if (instance == null) {
					instance = new Database();
				}
			}
		}
		return instance;
	}

	public Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, userName, password);
	}

	public static Connection connect() throws ClassNotFoundException,
			SQLException {
		Database database = Database.getInstance();
		return database.getConnection();
	}

	private void resetURL() {
		this.url = new StringBuilder("jdbc:mysql://").append(host).append(":")
				.append(port).append("/").append(dbName).toString();
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
		resetURL();
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
		resetURL();
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
		resetURL();
	}

	@Override
	public String toString() {
		return "Database [userName=" + userName + ", password=" + password
				+ ", host=" + host + ", port=" + port + ", dbName=" + dbName
				+ ", url=" + url + "]";
	}

}
